package com.suxin.lock;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Tang
 * @classname SyncMain
 * @description [  ]
 * @date 2021/3/6 16:02
 */
public class SyncMain {

    private static Object object = new Object();

    public static void main(String[] args) {
        SyncMain syncMain = new SyncMain();
        syncMain.run();
    }

    private void run() {
        System.out.println( "无锁的内存布局:" + ClassLayout.parseInstance(object).toPrintable());
        IntStream.range(1,3).forEach((i) -> {
            test02();
        });
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println( "无竞争之后的内存布局:" + ClassLayout.parseInstance(object).toPrintable());
        test02();
    }

    private synchronized void test01() {
        System.out.println("test...");
    }

    private void test02() {
        new Thread(() -> {
            synchronized (object) {
                System.out.println( "有锁的内存布局:" + ClassLayout.parseInstance(object).toPrintable());
                System.out.println("test...");
            }
        }).start();
    }
}